package controllers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
	"new/kpg/app"
	"new/kpg/e"
	"new/models"
	"new/services"
)

//查找学生信息
func GetStudent(c *gin.Context) {
	err, info, total := services.GetAllStudent()
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{"value": info, "total": total}, "查询成功")
}

//删除学生信息
func DelStudent(c *gin.Context) {
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	id := com.StrTo(m["Sno"]).MustInt()

	if id == -1 {
		app.INFO(c, 30001, "参数错误")
		return
	}
	err := services.DelStudent(id)
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "删除成功")
}

//更改学生信息
func UpdateStudent(c *gin.Context) {
	b, _ := c.GetRawData() //获取原始字节
	var m map[string]string
	_ = json.Unmarshal(b, &m) //将结构类型转换为json字符串，以下同理
	if m["Sno"] == "" {
		app.INFO(c, 30000, "参数非法")
		return
	}
	Sno := m["Sno"]
	Sname := m["Sname"]
	Ssex := m["Ssex"]
	Stel := m["Stel"]
	Sdept := m["Sdept"]
	Sclass := m["Sclass"]
	if Sno == "" {
		app.INFO(c, 30000, "参数非法")
		return
	}
	err := services.UpdateStudent(models.Student{Sno, Sname, Ssex, Stel, Sdept, Sclass})
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "更新成功")
}

//增加学生
func AddStudent(c *gin.Context) {
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	StudentSno := m["StudentSno"]
	StudentSname := m["StudentSname"]
	StudentSsex := m["StudentSsex"]
	StudentStel := m["StudentStel"]
	StudentSdept := m["StudentSdept"]
	StudentSclass := m["StudentSclass"]
	if StudentSno == "" {
		app.INFO(c, 30000, "参数非法")
		return
	}
	err := services.AddStudent(models.Student{StudentSno, StudentSname, StudentSsex, StudentStel, StudentSdept, StudentSclass})
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "添加成功")
}
